package com.ruoyi.data.filter.first;


import com.ruoyi.data.filter.first.JwtAccessTokenFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.web.HttpSecurityBuilder;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.authentication.logout.LogoutFilter;
import org.springframework.security.web.authentication.session.NullAuthenticatedSessionStrategy;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class AccessTokenConfig <T extends AbstractHttpConfigurer<T, B>, B extends HttpSecurityBuilder<B>>
        extends AbstractHttpConfigurer<T, B>{

    @Override
    public void configure(B builder) throws Exception {
        builder.addFilterAfter(jwtAccessTokenFilter(), LogoutFilter.class);
    }

    @Bean
    JwtAccessTokenFilter jwtAccessTokenFilter(){
        // 使用自定义的filter
        JwtAccessTokenFilter jwtAccessTokenFilter = new JwtAccessTokenFilter();
        // 新建providerManager并为filter配置provider
        List provider = new ArrayList<AuthenticationProvider>();
        AccessTokenProvider accessTokenProvider = new AccessTokenProvider();
        provider.add(accessTokenProvider);
        ProviderManager providerManager = new ProviderManager(provider);
        jwtAccessTokenFilter.setAuthenticationManager(providerManager);
        jwtAccessTokenFilter.setSessionAuthenticationStrategy(new NullAuthenticatedSessionStrategy());
        jwtAccessTokenFilter.setAuthenticationSuccessHandler(accessTokenSuccessHandler());
        jwtAccessTokenFilter.setAuthenticationFailureHandler(accessTokenFailureHandler());

        return jwtAccessTokenFilter;
    }

    @Bean
    AccessTokenSuccessHandler accessTokenSuccessHandler(){
        return new AccessTokenSuccessHandler();
    }

    @Bean
    AccessTokenFailureHandler accessTokenFailureHandler(){
        return new AccessTokenFailureHandler();
    }

}
